package com.hsnr.familyfinder;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    private DrawView drawView;
    private FileTools fileTools;
    private String group;
    private EditText groupName;
    private TextView height1, height2, height3, height4;
    private TextView lat1, lat2, lat3, lat4;
    private TextView long1, long2, long3, long4;
    private TextView name1, name2, name3, name4;
    private TextView startHeight;
    private TextView startLatitude;
    private TextView startLongitude;
    private Button startpunktSetzen;
    private TextView startTime;
    private final String TAG = "FamilyFinder";
    private TextView time1, time2, time3, time4;

    /**
     * @return the group
     */
    public String getGroup() {
        return group;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            Intent i = new Intent(this, Settings.class);
            startActivityForResult(i, 1);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * @param group
     *            the group to set
     */
    public void setGroup(String group) {
        this.group = group;
    }

    private void fillTable() {
        FileTools ft = new FileTools();
        ArrayList<HashMap<String, String>> rows = ft.parseCSV("db.csv");
        int i = 0;

        for (HashMap<String, String> h : rows) {
            h.put("height",h.get("height").substring(0, h.get("height").indexOf('.')));
            if (h.get("isStart").equals("1")) {
                startLatitude.setText(h.get("lat"));
                startLongitude.setText(h.get("lon"));
                startHeight.setText(h.get("height"));
                startTime.setText(toDate(h.get("time"), false));
            } else {
                switch (i) {
                case 0:
                    name1.setText(h.get("name"));
                    lat1.setText(h.get("lat"));
                    long1.setText(h.get("lon"));
                    height1.setText(h.get("height"));
                    time1.setText(toDate(h.get("time"), true));
                    break;
                case 1:
                    name2.setText(h.get("name"));
                    lat2.setText(h.get("lat"));
                    long2.setText(h.get("lon"));
                    height2.setText(h.get("height"));
                    time2.setText(toDate(h.get("time"), true));
                    break;
                case 2:
                    name3.setText(h.get("name"));
                    lat3.setText(h.get("lat"));
                    long3.setText(h.get("lon"));
                    height3.setText(h.get("height"));
                    time3.setText(toDate(h.get("time"), true));
                    break;
                case 3:
                    name4.setText(h.get("name"));
                    lat4.setText(h.get("lat"));
                    long4.setText(h.get("lon"));
                    height4.setText(h.get("height"));
                    time4.setText(toDate(h.get("time"), true));
                    break;
                }
                i++;
            }
        }
        drawView.setCoordinateData(rows);
        drawView.computeLageplan();
    }

    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

        return networkInfo != null && networkInfo.isConnected();
    }

    private void readConfig() {
        fileTools = new FileTools();
        String config = fileTools.read("config.txt");
        if (config != null && !config.equals("")) {
            String lb = System.getProperty("line.separator");
            String[] params = config.split(lb);
            for (int i = 0; i < params.length; i++) {
                try {
                    String[] kv = params[i].split("=", 2);
                    if(kv.length==2) {
                        writeToPreferences(kv[0],kv[1]);
                    }
                } catch (NullPointerException e) {
                    MyLog.e(TAG, "Fehler beim Lesen der Konfiguration! " + e.getMessage());
                }
                
                
            }
        }
    }

    private void setStartingPoint() {
        MyLog.d(TAG, "Startpunkt setzen");
        writeToPreferences("setStartingPoint", true);
    }

    private void startGPSService() {
        MyLog.d(TAG, "Anfrage: Starte Service");
        final SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        String ip = sharedPrefs.getString("server_ip", null);
        String name = sharedPrefs.getString("name", null);
        String group = sharedPrefs.getString("group", null);
        MyLog.d(TAG, "Wert von ip <" + ip + ">");
        MyLog.d(TAG, "Wert von name <" + name + ">");
        MyLog.d(TAG, "Wert von group <" + group + ">");
        if (isNetworkAvailable()) {
            Intent service;
            if (name != null && group != null && ip != null) {
                // Service Starten
                MyLog.d(TAG, "starte Service");
                service = new Intent(MainActivity.this, UpdateService.class);

            } else {
                service = new Intent(MainActivity.this, Settings.class);
            }

            startService(service);
        }

    }

    private String toDate(String timestamp, boolean timeOnly) {
        Date d = new Date(Long.parseLong(timestamp));
        StringBuilder sb = new StringBuilder();
        if (!timeOnly) {
            sb.append(d.getDate() + ".");
            sb.append(d.getMonth() + 1 + ".");
            sb.append((d.getYear() + 1900) + " ");
        }
        sb.append(((d.getHours() < 10) ? "0" : "") + d.getHours() + ":");
        sb.append(((d.getMinutes() < 10) ? "0" : "") + d.getMinutes());
        return sb.toString();
    }

    private void writeToPreferences(String key, Object value) {
        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = sharedPref.edit();
        if (value instanceof String) {
            editor.putString(key, (String) value);
        } else if (value instanceof Boolean) {
            editor.putBoolean(key, (Boolean) value);
        }
        editor.commit();
        MyLog.d(TAG, "Wertepaar <" + key + "> <" + value + "> in den Einstellungen gespeichert.");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        readConfig();

        try {
            // Steuerelemente initialisieren

            startLongitude = (TextView) findViewById(R.id.longitude);
            startLatitude = (TextView) findViewById(R.id.latitude);
            startHeight = (TextView) findViewById(R.id.height);
            startTime = (TextView) findViewById(R.id.time);

            long1 = (TextView) findViewById(R.id.lon1);
            lat1 = (TextView) findViewById(R.id.lat1);
            height1 = (TextView) findViewById(R.id.height1);
            time1 = (TextView) findViewById(R.id.time1);
            name1 = (TextView) findViewById(R.id.name1);

            long2 = (TextView) findViewById(R.id.lon2);
            lat2 = (TextView) findViewById(R.id.lat2);
            height2 = (TextView) findViewById(R.id.height2);
            time2 = (TextView) findViewById(R.id.time2);
            name2 = (TextView) findViewById(R.id.name2);

            long3 = (TextView) findViewById(R.id.lon3);
            lat3 = (TextView) findViewById(R.id.lat3);
            height3 = (TextView) findViewById(R.id.height3);
            time3 = (TextView) findViewById(R.id.time3);
            name3 = (TextView) findViewById(R.id.name3);

            long4 = (TextView) findViewById(R.id.lon4);
            lat4 = (TextView) findViewById(R.id.lat4);
            height4 = (TextView) findViewById(R.id.height4);
            time4 = (TextView) findViewById(R.id.time4);
            name4 = (TextView) findViewById(R.id.name4);
            final SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
            String group = sharedPrefs.getString("group", null);
            groupName = (EditText) findViewById(R.id.groupname);
            groupName.setOnKeyListener(new OnKeyListener() {
                public boolean onKey(View view, int keyCode, KeyEvent event) {
                    if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {

                        Toast.makeText(getApplicationContext(), "Gruppe wird gespeichert", Toast.LENGTH_SHORT).show();

                        setGroup(((EditText) view).getText().toString());
                        MyLog.d(TAG, "Group ist <" + getGroup() + ">");
                        writeToPreferences("group", getGroup());

                        startpunktSetzen.setEnabled(true);
                        fillTable();
                        return true;
                    } else {
                        return false;
                    }
                }
            });

            drawView = (DrawView) findViewById(R.id.drawView);
            drawView.setBackgroundColor(Color.WHITE);

            startpunktSetzen = (Button) findViewById(R.id.set_starting_point);
            startpunktSetzen.setEnabled(false);
            startpunktSetzen.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (MainActivity.this.group != null) {
                        MyLog.d(TAG, "Startpunkt setzen aufgerufen");
                        setStartingPoint();
                    } else {
                        Toast.makeText(getApplicationContext(), "Bitte erst einen Gruppennamen eingeben!", Toast.LENGTH_LONG)
                                .show();
                    }

                }
            });
            if (group != null) {
                groupName.setText(group);

                setGroup(group);
                MyLog.d(TAG, "Group ist <" + getGroup() + ">");
                writeToPreferences("group", getGroup());

                startpunktSetzen.setEnabled(true);
            }

             startGPSService();
        } catch (Exception e) {
            MyLog.e(TAG, "Es ist ein Fehler aufgetreten. " + e.getMessage());
            MyLog.e(TAG, "  Stacktrace: " + e.getStackTrace());
        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see android.app.Activity#onResume()
     */
    @Override
    protected void onResume() {
        fillTable();
        super.onResume();
    }

}
